import os

from rest_framework import serializers

from rest_framework_jwt.settings import api_settings
import time

from libs.script_discern import script_discerns
from user import models
from youzhu_api.settings import dev
from rest_framework.exceptions import APIException
from rest_framework_jwt.views import refresh_jwt_token
from libs.send_qinuiyun import qinui
from django.conf import settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
from celery_task.sms_task import send_sms
import random


# 登录
class LoginSerializers(serializers.ModelSerializer):
    username = serializers.CharField()
    icon = serializers.CharField(allow_blank=True, allow_null=True)

    # {"username":"竺新景",
    # "icon":"https://thirdwx.qlogo.cn/mmopen/vi_32/5UHydV26CHYIs1cmOWQHklFoWveNzxkumr8bwuSCdIGCdLg0Z0GpuicRZkEgZt0jRicoV0YiaHk53XCqvM9W5Bh1w/132"}
    class Meta:
        model = models.User
        fields = ['username', 'icon']

    def _chocke_data(self, username, icon):
        if not username and icon:
            raise APIException('用户名或头像不能为空')

    def _get_token(self, user):
        new_payload = jwt_payload_handler(user)
        token = jwt_encode_handler(new_payload)
        # print(token)
        return token

    def validate(self, attrs):  # {'username':'',"icon":icon}
        username = attrs.get('username')
        icon = attrs.get('icon')
        # 校验数据不能为空
        self._chocke_data(username, icon)
        # 签发token
        user, bol = models.User.objects.get_or_create(username=username, defaults={"icon": icon})
        # print(user.username)
        token = self._get_token(user)
        self.context['token'] = token
        self.context['id'] = user.id

        return attrs


# 修改信息
class AlterMessageSerializers(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = ['mobile', 'id_card', "addr"]

    def _get_id_card(self):
        request = self.context.get('request')
        file = request.FILES.get('file')

        if not file:
            raise APIException('文件不能为空')
        # 调取百度云识别身份证，返回身份证号
        discern_dict = script_discerns(file)
        # print(discern_dict)
        words = discern_dict['words_result']['公民身份号码']['words']
        addr = discern_dict['words_result']['住址']['words']

        return words, addr

    def _chock_data(self, mobile):
        if not mobile:
            raise APIException('数据不能为空')
        return True

    def validate(self, attrs):
        request = self.context.get('request')
        # 获取图片数据，上传百度云，获取身份证号
        id_card, addr = self._get_id_card()  # 获取到的身份证号

        mobile = attrs.get('mobile')  # 获取到用户手机号
        # print(mobile)
        self._chock_data(mobile)  # 判断数据是否为空，id是否存在
        user = request.user
        user.mobile = mobile
        user.id_card = id_card
        user.addr = addr
        user.save()
        code = random.randint(10000, 99999)
        res = send_sms.delay(mobile, code)    #发送验证码
        return attrs


class UserDetailSerializer(serializers.ModelSerializer):
    name = serializers.CharField()

    class Meta:
        model = models.User
        fields = ['name', 'desc']

    def _update_user(self, id, attrs):
        name = attrs.get('name')
        desc = attrs.get('desc')
        models.User.objects.filter(id=id).update(name=name, desc=desc)

    def _create_photo(self, id, photo):
        photo_obj = models.Photo.objects.create(userinfo_id=id, image=photo)
        photo_name = photo.name
        photo_addr = os.path.dirname(settings.BASE_DIR) + "/media/photo/" + photo_name
        photo_url = qinui.upload_img(photo_addr)
        photo_obj.qiniu_link = photo_url
        photo_obj.save()
        return photo_url

    def validate(self, attrs):  # {name:"昵称",desc:"座右铭"}
        name = attrs.get('name')
        desc = attrs.get('desc')
        # 拿到用户id，修改昵称，座右铭
        request = self.context.get('request')
        id = request.user.id
        self._update_user(id, attrs)
        # 拿到图片，保存，上传七牛云
        photo = request.FILES.get('photo')
        # print(photo)
        photo_url = self._create_photo(id, photo)
        self.context['photo_url'] = photo_url
        self.context['desc'] = desc
        self.context['name'] = name
        return attrs


class GetUserDetailModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = []
        # fields = ['name', 'desc']

    # def get_qiniu_link(self,obj):
    #     return obj.p_u.all().filter(is_delete=False, is_show=True).order_by("create_time").first()
    def validate(self, attrs):
        request = self.context.get('request')
        id = request.user.id
        print(id, '>>>>>')
        user_obj = models.User.objects.get(id=id)
        qiniu_link_obj = models.Photo.objects.filter(userinfo_id=id).all().order_by('-create_time').first()

        self.context['name'] = user_obj.name
        self.context['desc'] = user_obj.desc

        print(user_obj.name,user_obj.desc)
        try:
            self.context['qiniu_link'] = qiniu_link_obj.qiniu_link
        except Exception:
            pass
        return attrs
